<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class VariantAttribute extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'name',
        'slug',
        'type',
        'options',
        'is_required',
        'is_variant',
        'sort_order',
        'meta_data',
    ];

    protected $casts = [
        'options' => 'array',
        'is_required' => 'boolean',
        'is_variant' => 'boolean',
        'sort_order' => 'integer',
        'meta_data' => 'array',
    ];

    /**
     * 关联产品
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * 关联属性值
     */
    public function attributeValues(): HasMany
    {
        return $this->hasMany(VariantAttributeValue::class, 'attribute_id');
    }

    /**
     * 获取属性类型标签
     */
    public function getTypeLabelAttribute(): string
    {
        $labels = [
            'select' => '下拉选择',
            'color' => '颜色选择',
            'size' => '尺寸选择',
            'text' => '文本输入',
            'number' => '数字输入',
        ];

        return $labels[$this->type] ?? $this->type;
    }

    /**
     * 获取属性类型样式类
     */
    public function getTypeClassAttribute(): string
    {
        $classes = [
            'select' => 'bg-blue-100 text-blue-800',
            'color' => 'bg-purple-100 text-purple-800',
            'size' => 'bg-green-100 text-green-800',
            'text' => 'bg-gray-100 text-gray-800',
            'number' => 'bg-yellow-100 text-yellow-800',
        ];

        return $classes[$this->type] ?? 'bg-gray-100 text-gray-800';
    }

    /**
     * 作用域：按类型筛选
     */
    public function scopeOfType($query, string $type)
    {
        return $query->where('type', $type);
    }

    /**
     * 作用域：必选属性
     */
    public function scopeRequired($query)
    {
        return $query->where('is_required', true);
    }

    /**
     * 作用域：影响变体的属性
     */
    public function scopeVariantAffecting($query)
    {
        return $query->where('is_variant', true);
    }

    /**
     * 作用域：按排序
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'desc')->orderBy('created_at', 'desc');
    }
}